import csv
import unittest
from BeautifulReport import BeautifulReport


class MakeTestCases:
    testcases = []

    def __init__(self):
        with open('../params.csv', 'r', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            row_num = 0
            for row in reader:
                self.testcases.append(row)
            print('testcases:-----------------------------------------')
            print(self.testcases)

    def make_test_func(self, case):
        def func(expect, actual_res):
            """
            测试方法，传入测试步骤，构建测试步骤
            """
            assert expect in actual_res
        return func

    def make_test_class(self, *args, **kwargs):
        # 自动创建测试类，并继承unittest.TestCase
        return type("TestContact", (unittest.TestCase,), {})

    def make(self):
        #获取动态类
        test_class = self.make_test_class()
        #用来保存所有测试方法
        tests = []
        for case in self.testcases:
            test_func = self.make_test_func(case['testcase_title'])
            # test_name = "test_%s" % case['keywords']
            test_name = "test_%s" % case['keywords']
            #动态生成测试方法
            setattr(test_class, test_name, test_func)
            # 测试方法保存到此变量，添加到testsuite
            tests.append(test_class(test_name))
        return test_class
    #可以通过多种方法添加
     #  return tests


def test_report():
    cases = MakeTestCases().make()

    testsuite = unittest.TestSuite()

    testsuite.addTests(unittest.TestLoader().loadTestsFromTestCase(cases))

    # runner = unittest.TextTestRunner(verbosity=2)
    #
    # runner.run(testsuite)

    br = BeautifulReport(testsuite)
    br.report(description='', filename='../report/test_report.html')
